import requests
import json
from typing import Dict, Any, List, Optional, Union, Tuple


def send_post_request(
        url: str,
        data: Union[Dict[str, Any], List[Any]],
        headers: Dict[str, str] = None,
        files: Optional[Dict[str, Tuple[str, bytes, str]]] = None,
        params: Optional[Dict[str, Any]] = None,
        timeout: int = 30,
        verify: bool = True
) -> Dict[str, Any]:
    """
    发送POST请求到指定URL，支持集合类型参数

    参数:
        url: 请求的目标URL
        data: 要发送的数据，可以是字典或列表
        headers: 自定义请求头
        files: 文件上传参数，格式为 {字段名: (文件名, 文件内容, 文件类型)}
        params: URL查询参数
        timeout: 请求超时时间（秒）
        verify: 是否验证SSL证书

    返回:
        包含响应信息的字典
    """
    try:
        # 处理不同类型的data参数
        if files:
            # 文件上传场景，使用form-data编码
            payload = data
            request_headers = headers or {}
        else:
            # JSON格式请求
            payload = json.dumps(data)
            request_headers = {
                'Content-Type': 'application/json',
                **(headers or {})
            }

        # 发送POST请求
        response = requests.post(
            url,
            data=payload,
            headers=request_headers,
            files=files,
            params=params,
            timeout=timeout,
            verify=verify
        )

        # 处理响应
        result = {
            'success': response.status_code in (200, 201),
            'status_code': response.status_code,
            'headers': dict(response.headers)
        }

        # 尝试解析JSON响应
        try:
            result['data'] = response.json()
        except json.JSONDecodeError:
            result['data'] = response.text

        return result

    except requests.exceptions.RequestException as e:
        return {
            'success': False,
            'message': f'请求出错: {str(e)}',
            'error_type': type(e).__name__
        }


def main():
    # 示例1：发送列表参数
    product_ids = [101, 102, 103, 104]
    response1 = send_post_request(
        "https://api.example.com/products/batch",
        product_ids
    )
    print("示例1响应:", json.dumps(response1, indent=2))

    # 示例2：发送包含集合的对象
    order_data = {
        "order_id": "ORD-20231001",
        "products": [
            {"id": 101, "name": "iPhone 15", "quantity": 1},
            {"id": 202, "name": "AirPods Pro", "quantity": 2}
        ],
        "total_amount": 7997.0
    }
    response2 = send_post_request(
        "https://api.example.com/orders",
        order_data
    )
    print("示例2响应:", json.dumps(response2, indent=2))

    # 示例3：发送嵌套集合
    batch_data = {
        "requests": [
            {"action": "create", "data": {"name": "Product A"}},
            {"action": "update", "data": {"id": 101, "price": 999}}
        ]
    }
    response3 = send_post_request(
        "https://api.example.com/batch",
        batch_data
    )
    print("示例3响应:", json.dumps(response3, indent=2))


if __name__ == "__main__":
    main()